<template>
  <el-dialog
      v-model="showDialog"
      :title="title"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @close="handleCloseDialog(menuInfoRef)"
      @closed="handleClosedDialog"
      @open="handleOpenDialog"
      @opened="handleOpenedDialog"
  >
    <el-form
        :model="menuInfo"
        :rules="menuInfoRules"
        ref="menuInfoRef"
        label-suffix=":"
        label-width="100px"
        status-icon
    >
      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="menuInfo.menuName" type="text"></el-input>
      </el-form-item>
      <el-form-item label="菜单路径" prop="menuPath">
        <el-input v-model="menuInfo.menuPath" type="text"></el-input>
      </el-form-item>
      <el-form-item label="菜单类型" prop="menuType">
        <el-select v-model="menuInfo.menuType">
          <el-option v-for="item in menuTypeData" :value="item.value" :label="item.label"
                     :key="item.key || item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜单排序" prop="orderNum">
        <el-input v-model="menuInfo.orderNum" type="number"></el-input>
      </el-form-item>
      <el-form-item label="是否使用" prop="isUse">
        <el-select v-model="menuInfo.isUse">
          <el-option v-for="item in isUseData" :value="item.value" :label="item.label"
                     :key="item.key || item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属模块" prop="owningModule">
        <el-select v-model="menuInfo.owningModule">
          <el-option v-for="item in owningModuleData" :value="item.value" :label="item.label"
                     :key="item.key || item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="父级节点" prop="parentId">
        <el-select v-model="menuInfo.parentId" :clearable="true" :filterable="true">
          <el-option v-for="item in parentData" :value="item.value" :label="item.label"
                     :key="item.key || item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="confirm(menuInfoRef)" :loading="confirmLoading">保存</el-button>
      <el-button type="danger" @click="closeDialog(menuInfoRef)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {DIALOG_EDIT, DIALOG_VIEW} from "@/constants/common-constant.ts";
import {reactive, ref, watch} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import {dictDataUtil} from "@/utils/common-request.ts";
import {SYSTEM_MENU_IS_USE, SYSTEM_MENU_TYPE, SYSTEM_MODULE} from "@/constants/dict-constants.ts";
import {getParentMenuDropDownReq, saveMenuReq} from "@/api/admin/menu.ts";
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {formatObjToStr} from "@/utils/format-utils.ts";

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  dialogType: {
    type: String,
    default: DIALOG_VIEW
  },
  dialogParam: {
    type: Object,
    default: () => {
    }
  }
})

const emits = defineEmits(['handleCloseDialog', 'handleClosedDialog', 'handleOpenDialog', 'handleOpenedDialog'])

const showDialog = ref(props.showDialog)
watch(() => props.showDialog, (val: boolean) => {
  showDialog.value = val
})

interface MenuInfo {
  id: string;
  menuName: string;
  menuPath: string;
  menuType: string;
  orderNum: number;
  isUse: string;
  owningModule: string;
  parentId: string;
}

const menuInfo = reactive<MenuInfo>({
  id: '',
  menuName: '',
  menuPath: '',
  menuType: '',
  orderNum: 1,
  isUse: '',
  owningModule: '',
  parentId: ''
})

const menuInfoRef = ref<FormInstance>();

const menuInfoRules = reactive<FormRules<MenuInfo>>({
  menuName: [
    {required: true, message: '请输入菜单名称', trigger: 'blur'},
  ],
  menuPath: [
    {required: true, message: '请输入菜单路径', trigger: 'blur'}
  ],
  menuType: [
    {required: true, message: '请选择菜单类型', trigger: 'change'}
  ],
  isUse: [
    {required: true, message: '请选择是否使用', trigger: 'change'}
  ],
  owningModule: [
    {required: true, message: '请选择所属模块', trigger: 'change'}
  ]
})

const menuTypeData = ref<any>([])
const isUseData = ref<any>([])
const owningModuleData = ref<any>([])
const parentData = ref<any>([])

const initMenuTypeData = async () => {
  menuTypeData.value = await dictDataUtil(SYSTEM_MENU_TYPE)
}
const initIsUseData = async () => {
  isUseData.value = await dictDataUtil(SYSTEM_MENU_IS_USE)
}
const initOwningModuleData = async () => {
  owningModuleData.value = await dictDataUtil(SYSTEM_MODULE)
}
const initParentData = async () => {
  const res: any = await getParentMenuDropDownReq({})
  if (res.code === RESPONSE_CODE_SUCCESS) {
    parentData.value = res.data
  } else {
    parentData.value= []
  }

}

const initData = () => {
  const newDialogParam = props.dialogParam.node
  menuInfo.menuName = newDialogParam.menuName
  menuInfo.menuPath = newDialogParam.menuPath
  menuInfo.menuType = formatObjToStr(newDialogParam.menuType)
  menuInfo.orderNum = newDialogParam.orderNum
  menuInfo.isUse = formatObjToStr(newDialogParam.isUse)
  menuInfo.owningModule = formatObjToStr(newDialogParam.owningModule)
  menuInfo.parentId = newDialogParam.parentId === '0' ? '' : newDialogParam.parentId
}

const handleCloseDialog = (formEl: FormInstance | undefined) => {
  reset(formEl)
  emits('handleCloseDialog', false)
}

const handleClosedDialog = () => {
  emits('handleClosedDialog', false)
}

const handleOpenDialog = () => {
  emits('handleOpenDialog')
}

const handleOpenedDialog = () => {
  emits('handleOpenedDialog')
  initMenuTypeData().then()
  initIsUseData().then()
  initOwningModuleData().then()
  initParentData().then()
  if(props.dialogType == DIALOG_EDIT) {
    initData()
  }
}

const confirmLoading = ref<boolean>(false)
const confirm = async (formEl: FormInstance | undefined) => {
  if(!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid){
      warningMessageTip("请填写完整信息")
      return;
    } else {
      commonConfirm(formEl)
    }
  })
}

const commonConfirm = async (formEl: FormInstance | undefined) => {
  confirmLoading.value = true

  const params = {
    id: props.dialogParam.id,
    menuName: menuInfo.menuName,
    menuPath: menuInfo.menuPath,
    menuType: menuInfo.menuType,
    orderNum: menuInfo.orderNum,
    isUse: menuInfo.isUse,
    owningModule: menuInfo.owningModule,
    parentId: menuInfo.parentId
  }
  const res:any = await saveMenuReq(params)
  elMessageTip(res.tipType, res.message)
  confirmLoading.value = false
  if (res.code === RESPONSE_CODE_SUCCESS) {
    closeDialog(formEl)
  }

}

const closeDialog = (formEl: FormInstance | undefined) => {
  reset(formEl)
  emits('handleCloseDialog', false)
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>

<style scoped>

</style>